package org.eweb4j.solidbase.user.web.inter;

import java.util.List;

import javax.servlet.http.HttpSession;

import org.eweb4j.ioc.IOC;
import org.eweb4j.mvc.config.bean.ActionConfigBean;
import org.eweb4j.mvc.interceptor.Interceptor;
import org.eweb4j.solidbase.permission.model.Permission;
import org.eweb4j.solidbase.permission.model.PermissionCons;
import org.eweb4j.solidbase.permission.model.PermissionService;
import org.eweb4j.solidbase.role.model.Role;
import org.eweb4j.solidbase.role.model.RoleCons;
import org.eweb4j.solidbase.role.model.RoleService;
import org.eweb4j.solidbase.user.model.User;
import org.eweb4j.solidbase.user.model.UserActivityLog;
import org.eweb4j.solidbase.user.model.UserActivityLogCons;
import org.eweb4j.solidbase.user.model.UserActivityLogService;
import org.eweb4j.util.StringUtil;

/**
 * 鉴权过滤器
 * 
 * @author weiwei
 * @since JDK 1.5
 * @CopyRight WinOn Ltd.2012 All Rights Reserved
 * @version Gateway-1.0.0-SNAPSHOT
 * 
 */
public class PermissionVerifyFilter extends Interceptor {
	HttpSession session;
	private User loginUser;
	private List<Role> roles;
	private RoleService roleService = IOC.getBean(RoleCons
			.IOC_SERVICE_BEAN_ID());
	private PermissionService permService = IOC.getBean(PermissionCons
			.IOC_SERVICE_BEAN_ID());
	private String permName = "";
	private String actionName = null;

	private UserActivityLogService logService = IOC.getBean(UserActivityLogCons
			.IOC_SERVICE_BEAN_ID());

	private UserActivityLog log = new UserActivityLog();

	private boolean isSuccess = false;
	private String mess = null;

	@Override
	public String intecept() {
		String uri = this.context.getUri();
		if (uri.length() == 0)
			uri = " ";
		if (uri.endsWith("/"))
			uri = uri.substring(0, uri.length()-1);
		
		ActionConfigBean actionBean = this.context.getMvcBean();
		String httpMethod = this.context.getHttpMethod();
		session = this.context.getRequest().getSession(true);
		loginUser = (User) session.getAttribute("loginUser");
		if (loginUser == null)
			return null;

		// 该用户拥有超能力，可以免权限检查
		if ("yes".equals(loginUser.getSuperPower()))
			return null;

		roles = loginUser.getRoles();
		if (roles == null) {
			session.invalidate();
			return "<script>alert('当前登录的账户没有任何角色权限'); history.go(-1)</script>";
		}

		try {
			// 获得权限名称
			Permission permission = permService.findByURIAndHttpMethod(uri,
					httpMethod);
			if (permission == null)
				permission = permService.findByURIAndHttpMethod(
						this.actionName, httpMethod);

			if (permission == null)
				return null;// 没有被定义成权限的不需要控制

			permName = permission.getName();
			log.setUser(loginUser);
			log.setUserAccount(loginUser.getAccount());
			log.setUserName(loginUser.getTrueName());
			log.setTime(StringUtil.getNowTime());

			if (actionBean != null) {
				actionName = actionBean.getName();
				httpMethod = actionBean.getReqMethod();
			}

			

			// user log
			log.setActivity(permName);

			role_item: for (Role r : roles) {

				Role role = roleService.findPermissionByRoleId(r.getRoleId());
				List<Permission> perms = role.getPermissions();

				if (perms == null || perms.size() == 0)
					continue;

				for (Permission perm : perms) {
					// 权限通过
					if (permission != null
							&& permission.getPermId() == perm.getPermId()) {
						isSuccess = true;
						break role_item;
					}
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			mess = "系统出现异常：" + e.toString();
			isSuccess = false;
		}

		mess = mess == null ? String
				.format("用户权限不足, 无法执行[%s]功能", this.permName) : mess;

		if (isSuccess) {
			log.setResult("success");
		} else {
			log.setResult("false");
			log.setFailureCause(mess);
		}

		try {
			logService.createLogInfo(log);
			if (isSuccess)
				return null;
		} catch (Exception e) {
			e.printStackTrace();
			mess = e.toString();
		}

		return "<script>alert('" + mess + "')</script>";
	}
}
